#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd

import re
import base64
import Lib.Logger.log4py as logging
from mj_parser import common_errors


def find_string(html, name):
    p = re.compile('<' + name + '>.+?</' + name + '>', re.S)
    html_div_chn_li = p.findall(html)
    if html_div_chn_li is not None and len(html_div_chn_li) > 0:
        return html_div_chn_li[0].replace('<' + name + '>', '').replace('</' + name + '>', '')
    else:
        return ''


class AudiParserETK:
    default_result = {
        'model': '',
        'year': '',
        'manufacture_date': '',
        'type': '',
        'engine': '',
        'transmission': '',
        'body': '',
        'setting': '',
        'inner_color': '',
        'color': '',
        'manufacturer': '',
        'production_code': '',
        'engine_number': '',
        'country_symbol': '',
        'content': '',
        'brand': '',
        'pr_list': '',
        'raw_content': ''
    }

    def __init__(self, root_dir="."):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "AudiParserETK")

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            with open(file_name, encoding='utf_8_sig') as fobj:
                html = fobj.read()

                result_list['year'] = find_string(html, 'ModelYear')
                result_list['manufacture_date'] = find_string(html, 'ProductionDate')
                result_list['type'] = find_string(html, 'SalesType')
                result_list['engine'] = find_string(html, 'EngineCode')
                result_list['transmission'] = find_string(html, 'TransmissionCode')
                result_list['body'] = ''
                result_list['model'] = ''
                result_list['color'] = find_string(html, 'Paint')
                result_list['manufacturer'] = find_string(html, 'Manufacturer')
                result_list['production_code'] = find_string(html, 'ProductionCode')
                result_list['engine_number'] = find_string(html, 'EngineNumber')
                result_list['country_symbol'] = find_string(html, 'CountrySymbol')
                result_list['brand'] = find_string(html, 'Brand')
                result_list['raw_content'] = base64.b64encode(html.encode('utf-8')).decode('utf-8')

                p = re.compile('<Color type="interior">.+?</Color>', re.S)
                html_div_chn_li = p.findall(html)
                if html_div_chn_li is not None and len(html_div_chn_li) > 0:
                    result_list['setting'] = html_div_chn_li[0].replace('<Color type="interior">', '').replace(
                        '</Color>',
                        '')
                else:
                    result_list['setting'] = ''

                p = re.compile('<Color type="top">.+?</Color>', re.S)
                html_div_chn_li = p.findall(html)
                if html_div_chn_li is not None and len(html_div_chn_li) > 0:
                    result_list['inner_color'] = html_div_chn_li[0].replace('<Color type="top">', '').replace(
                        '</Color>',
                        '')
                else:
                    result_list['inner_color'] = ''

                p = re.compile('<PR>.+?</PR>', re.S)
                html_div_chn_li = p.findall(html)

                if html_div_chn_li is not None and len(html_div_chn_li) > 0:
                    li = []
                    for x in html_div_chn_li:
                        x = x.replace('<PR>', '').replace('</PR>', '')
                        li.append(x)
                    result_list['pr_list'] = '|'.join(li)
                else:
                    result_list['pr_list'] = ''
                    b=common_errors.ERR_NO_CONTENT
                    self.logger.error('pr_list is empty.')

        except Exception as ex:
            self.logger.error(ex)
            b = common_errors.ERR_UNKNOWN
        return b, result_list

    def get_default_result(self):
        return AudiParserETK.default_result.copy()
